# -*- coding: utf-8 -*-

import logging
import time_ext_

import paho.mqtt.client as mqtt

log = logging.getLogger('main.mqtt')
log.setLevel(0)


class MqttClient(object):
    """docstring for MqttClient"""
    mode = {0: '只发一次', 1: '最多一次', 2: '保证一次'}

    def __init__(self, host, send_topic = None, receive_topic = None, port = 1883, user = None, password = None,
                 qos = 2):
        super(MqttClient, self).__init__()
        self.log = log
        self.user = user
        self.password = password
        self.host = host
        self.port = port
        self.send_topic = send_topic
        self.receive_topic = receive_topic
        self.qos = qos
        self.client = mqtt.Client(str(time_ext_.time() * 1000))

    def start(self):
        self.client.on_connect = self.on_connect  # 连接回调
        self.client.on_message = self.on_message  # 消息回调
        self.client.on_subscribe = self.on_subscribe  # 订阅回调
        self.client.on_publish = self.on_publish  # 发送回调
        self.client.on_disconnect = self.on_disconnect  # 断开回调
        self.client.connect(self.host, self.port, 60)  # 连接
        self.client.username_pw_set(self.user, self.password)  # 设置帐号密码
        self.client.subscribe("send", self.qos)  # 订阅消息
        # self.client.loop_forever()

    def colse(self):
        self.client.loop_stop()
        self.client.disconnect()

    # 连接回调
    def on_connect(self, client, userdata, flags, rc):
        msg = {
                0: '连接成功',
                1: '协议版本错误',
                2: '无效的客户端标识',
                3: '服务器无法使用',
                4: '错误的用户名或密码',
                5: '未经授权',
                }
        info = "客户端:{},连接MQTT服务:{},端口:{},结果:{}".format(client._client_id, client._host, client._port, msg.get(rc))
        self.log.info(info)
        self.client.loop_start()
        print(info)

    # 发送后回调
    def on_publish(self, client, userdata, mid):
        info = "发送数据成功"
        self.log.info(info)
        print(info)

    # 接收数据回调
    def on_message(self, client, userdata, msg):
        topic = msg.topic
        data = msg.payload.decode()
        info = "接收到主题:{},消息:{}".format(topic, data)
        print(info)
        self.log.info(info)

    # 订阅主题回调
    def on_subscribe(self, client, userdata, mid, qos):
        info = "订阅主题:{},消息模式:{}".format(self.receive_topic, self.mode.get(qos[0]))
        self.log.info(info)
        print(info)

    # 断开回调
    def on_disconnect(self, client, userdata, rc):
        if rc != 0:
            info = "异外断开"
            return info
        return "正常断开"

    # 发送数据
    def send(self, data):
        return self.client.publish(self.send_topic, data, self.qos)


if __name__ == '__main__':
    app = MqttClient('127.0.0.1', send_topic = 'send', receive_topic = 'send')
    app.start()
    app.send('xxx')
    app.colse()
    # while 1:
    #
    #     pass
# # 连接MQTT服务器
# def on_mqtt_connect():
#     mqttClient.connect(MQTTHOST, MQTTPORT, 60)
#     mqttClient.loop_start()
#
#
# def on_connect(client, userdata, flags, rc):
#     print("Connected with result code " + str(rc))
#     client.subscribe("send")  # 订阅消息
#
#
# # 消息处理函数
# def on_message(client, userdata, msg):
#     print("主题:" + msg.topic + " 消息:" + str(msg.payload.decode('utf-8')))
#
#
# # subscribe 消息订阅
# def on_subscribe(client, userdata, mid, granted_qos):
#     print("On Subscribed: qos = %d" % granted_qos)
#
#
# def on_disconnect(client, userdata, rc):
#     if rc != 0:
#         print("Unexpected disconnection %s" % rc)
#
#
# data = {
#         "type": 2,
#         "timestamp": time.time(),
#         "messageId": "9fcda359-89f5-4933-xxxx",
#         "command": "xx/recommend",
#         "data": {
#                 "openId": "xxxx",
#                 "appId": 121414,
#                 "recommendType": "temRecommend"
#                 }
#         }
# param = json.dumps(data)
# client = mqtt.Client(client_id)
# client.username_pw_set("xxxxxx", "xxxxxx")
# client.on_connect = on_connect
# client.on_message = on_message
# client.on_subscribe = on_subscribe
# client.on_disconnect = on_disconnect
# client.connect(HOST, PORT, 60)
# client.publish("send", payload = param, qos = 0)  # 发送消息
# client.loop_forever()